﻿using SlamDunk.CMS.BLL;
using SlamDunk.CMS.Model;
using SlamDunk.CMS.Model.FormatModel;
using SlamDunk.CMS.Model.ViewModel;
using SlamDunk.CMS.UI.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web.Mvc;
using SlamDunk.CMS.Model.DataModel;

namespace SlamDunk.CMS.UI.Areas.Admin.Controllers
{
    /// <summary>
    /// Photo控制器
    /// </summary>
    public class PhotoController : BaseController
    {
        #region 00.实例化业务层对象
        /// <summary>
        /// 实例化业务层对象
        /// </summary>
        private readonly PhotoBll PhotoBll = new PhotoBll();
        private readonly PhotoAlbumBll PhotoAlbumBll = new PhotoAlbumBll();
        private readonly List<PhotoAlbum> photoAlbumList;

        /// <summary>
        /// 构造方法
        /// </summary>
        public PhotoController()
        {
            this.photoAlbumList = this.PhotoAlbumBll.GetModelList();
        }
        #endregion

        #region 01.加载视图
        /// <summary>
        /// 加载列表视图
        /// </summary>
        /// <returns>列表视图</returns>
        public ActionResult Index()
        {
            this.ViewBag.AlbumList = this.photoAlbumList;
            return this.View();
        }
        #endregion

        #region 02.加载列表
        /// <summary>
        /// 加载列表
        /// </summary>
        /// <returns>EasyUI要求的json格式数据</returns>
        public ActionResult List()
        {
            //1.获取EasyUI请求的数据
            int pageIndex = string.IsNullOrEmpty(this.Request["page"]) ? 1 : int.Parse(this.Request["page"]);
            int pageSize = string.IsNullOrEmpty(this.Request["rows"]) ? 10 : int.Parse(this.Request["rows"]);
            int albumId = string.IsNullOrEmpty(this.Request["album"]) ? 0 : int.Parse(this.Request["album"]);
            //2.根据请求查询数据并转换视图模型
            int pageCount, rowCount;
            List<PhotoView> list = this.PhotoBll.GetModelList(pageIndex, pageSize, out pageCount, out rowCount, albumId).Select(x => x.ToViewModel()).ToList();
            //封装EasyUI模型
            DataGridModel dgModel = new DataGridModel()
            {
                total = rowCount,
                rows = list
            };
            //返回数据
            return this.Json(dgModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 03.添加——加载视图
        /// <summary>
        /// 添加——加载视图
        /// </summary>
        /// <returns>添加视图</returns>
        public ActionResult Add()
        {
            this.ViewBag.AlbumList = this.photoAlbumList;
            return this.View();
        }
        #endregion

        #region 04.添加——提交添加
        /// <summary>
        /// 添加——提交添加
        /// </summary>
        /// <param name="model">视图模型</param>
        /// <returns>JsonModel</returns>
        public ActionResult AddConfirm(PhotoView model)
        {
            //校验模型
            if (this.ModelState.IsValid)
            {
                //1.转换数据模型
                Photo dataModel = model.ToDataModel();
                //2.获取添加后的数据模型
                Photo newModel = this.PhotoBll.Add(dataModel);

                #region 相册封面处理
                //相册封面处理，设置最新的图片为相册封面
                PhotoAlbum currentAlbum = newModel.PhotoAlbum;
                currentAlbum.Cover = newModel.ImagePath;
                this.PhotoAlbumBll.Update(currentAlbum);
                #endregion

                //3.非空校验
                if (newModel != null)
                {
                    //生成静态页
                    ThreadPool.QueueUserWorkItem(x =>
                    {
                        this.CreateHomeHtml();
                    });
                    return OperateContext.Current.JsonModel(1, "添加成功！");
                }
                else
                {
                    return OperateContext.Current.JsonModel(0, "添加失败！");
                }
            }
            else    //模型校验失败
            {
                return OperateContext.Current.JsonModel(0, "您提交的数据有误，请重试！");
            }
        }
        #endregion

        #region 05.删除单行
        /// <summary>
        /// 删除单行
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>JsonModel</returns>
        public ActionResult DeleteSingle(int id)
        {
            //1.查询该实体是否存在
            Photo model = this.PhotoBll.GetModel(id);
            if (model == null)
            {
                return OperateContext.Current.JsonModel(0, "该实体不存在！");
            }
            else //2.如果存在，则删除
            {
                if (this.PhotoBll.PhysicalDelete(id))
                {
                    //生成静态页
                    ThreadPool.QueueUserWorkItem(x =>
                    {
                        this.CreateHomeHtml();
                    });
                    return OperateContext.Current.JsonModel(1, "删除成功！");
                }
                else
                {
                    return OperateContext.Current.JsonModel(2, "删除失败，请重试！");
                }
            }
        }
        #endregion

        #region 06.删除选中行
        /// <summary>
        /// 删除选中的所有行
        /// </summary>
        /// <param name="selectedIds">选中行的Id</param>
        /// <returns>JsonModel</returns>
        public ActionResult DeleteSelected(string selectedIds)
        {
            try                 //涉及多次类型转换等操作，应处理异常
            {
                //1.处理前台选中的所有要删除的实体Id信息
                List<int> idList = selectedIds.Split(',').Select(x => int.Parse(x)).ToList();
                //2.执行批量删除操作
                idList.ForEach(x => this.PhotoBll.PhysicalDelete(x));
                //生成静态页
                ThreadPool.QueueUserWorkItem(x =>
                {
                    this.CreateHomeHtml();
                });
                return OperateContext.Current.JsonModel(1, "删除成功！");
            }
            catch (Exception ex)
            {
                //写入日志

                //返回异常信息
                return OperateContext.Current.JsonModel(0, string.Format("删除失败，{0}", ex.Message));
            }
        }
        #endregion

        #region 07.修改—加载视图
        /// <summary>
        /// 加载要修改的行
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>修改视图</returns>
        public ActionResult Edit(int id)
        {
            //1.根据给定主键查询数据模型并转化为视图模型
            PhotoView viewModel = this.PhotoBll.GetModel(id).ToViewModel();
            this.ViewBag.AlbumList = this.photoAlbumList;
            //2.返回视图 + 视图模型
            return this.View(viewModel);
        }
        #endregion

        #region 08.修改—提交修改
        /// <summary>
        /// 提交修改
        /// </summary>
        /// <param name="viewModel">视图模型</param>
        /// <returns>JsonModel</returns>
        public ActionResult EditConfirm(PhotoView viewModel)
        {
            //校验模型
            if (this.ModelState.IsValid)
            {
                //*判断相册封面
                Photo photoModel = this.PhotoBll.GetModel(viewModel.Id);
                PhotoAlbum albumModel = this.PhotoAlbumBll.GetModel(photoModel.AlbumId);
                if (albumModel.Cover == photoModel.ImagePath)
                {
                    albumModel.Cover = viewModel.ImagePath;
                    this.PhotoAlbumBll.Update(albumModel);
                }
                //1.将用户提交的视图模型转换为数据模型
                Photo model = viewModel.ToDataModel();
                //2.执行修改操作
                if (this.PhotoBll.Update(model))
                {
                    //生成静态页
                    ThreadPool.QueueUserWorkItem(x =>
                    {
                        this.CreateHomeHtml();
                    });
                    return OperateContext.Current.JsonModel(1, "修改成功！");
                }
                else
                {
                    return OperateContext.Current.JsonModel(0, "修改失败，请重试！");
                }
            }
            else    //模型校验失败
            {
                return OperateContext.Current.JsonModel(0, "您提交的数据有误，请重试！");
            }
        }
        #endregion
    }
}
